import React, { useState } from "react";
import { useSelector, useDispatch } from 'react-redux';
import { CRow, CFormInput, CButton, CCol, CFormLabel, CCard, CTable, CTableHead, CTableRow, CTableHeaderCell, CTableBody, CTableDataCell } from '@coreui/react';
import { setDoctorDataState } from '../../actions/auth';
import { Link, useNavigate } from 'react-router-dom';

const DoctorInfo = () => {
    const [username, setUsername] = useState('');
    const [doctorData, setDoctorData] = useState({});
    const [userId, setUserId] = useState(null);
    const [message, setMessage] = useState('');
    const token = useSelector((state) => state.token);
    const dispatch = useDispatch()
    const doctorDataState = useSelector((state) => state.doctorData);
    const navigate = useNavigate();

    const handleSubmitFind = async (e) => {
        e.preventDefault();
        try {
            const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/users/find_by_username?username=${encodeURIComponent(username)}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
            });
            const data = await response.json();
            if (data.username) {
                setDoctorData(data);
                setUserId(data.id);
                setMessage('')
            } else {
                setDoctorData({})
                setMessage('Пользователь не найден');
            }
        } catch (error) {
            console.error("Failed to find user:", error);
            setMessage('Ошибка при поиске пользователя');
        }
    };

    const toggleEditMode = () => {
        dispatch(setDoctorDataState(doctorData))
        navigate('/add_doctor')
    };

    return (
        <div>
            <h1>Информация по врачу</h1>
            <br></br>
            <form onSubmit={handleSubmitFind}>
                <CRow>
                    <CCol xs={6}>
                        <CFormInput
                            type="text"
                            placeholder="Фамилия Имя Отчество"
                            aria-label="Username"
                            value={username}
                            onChange={(e) => setUsername(e.target.value)}
                        />
                    </CCol>
                    <CCol xs={3}>
                        <CButton color="light" variant="outline" type="submit">Найти</CButton>
                    </CCol>
                </CRow>
                <br></br>
                <CRow>
                    
                </CRow>
            </form>
            <br></br>
            <CCard style={{ width: '45rem' }}>
                <CTable>
                    <CTableBody>
                        <CTableRow>
                            <CTableHeaderCell scope="row">ФИО</CTableHeaderCell>
                            <CTableDataCell>{doctorData.username}</CTableDataCell>
                        </CTableRow>
                        <CTableRow>
                            <CTableHeaderCell scope="row">Модальность</CTableHeaderCell>
                            <CTableDataCell>{doctorData.modality}</CTableDataCell>
                        </CTableRow>
                        <CTableRow>
                            <CTableHeaderCell scope="row">Ставка</CTableHeaderCell>
                            <CTableDataCell>{doctorData.employment_rate}</CTableDataCell>
                        </CTableRow>
                        <CTableRow>
                            <CTableHeaderCell scope="row">Начало работы</CTableHeaderCell>
                            <CTableDataCell>{doctorData.start_work}</CTableDataCell>
                        </CTableRow>
                        <CTableRow>
                            <CTableHeaderCell scope="row">Статус</CTableHeaderCell>
                            <CTableDataCell>{doctorData.status}</CTableDataCell>
                        </CTableRow>
                        <CTableRow>
                            <CTableHeaderCell scope="row">Дополнительные модальности</CTableHeaderCell>
                            <CTableDataCell>
                                {doctorData.additional_modality? 
                                    doctorData.additional_modality.map((modality, index) => (
                                        <span key={index}>{modality.name}, </span>
                                    ))
                                : 
                                    ""
                                }
                            </CTableDataCell>
                        </CTableRow>
                    </CTableBody>
                </CTable>
                
            </CCard>
            <br></br>
            <CCol xs={3}>
                <CButton color="light" variant="outline" type="submit" onClick={toggleEditMode}>Редактировать</CButton>
            </CCol>
            <CRow>
                <CFormLabel htmlFor="staticEmail" className="col-sm-12 col-form-label">{message}</CFormLabel>
            </CRow>
        </div>
    );
};

export default DoctorInfo;
